package com.jluzh10.learning.web.controller;

import com.jluzh10.learning.domain.Course;
import com.jluzh10.learning.domain.User;
import com.jluzh10.learning.service.UserService;
import com.jluzh10.learning.utils.ResponseData;
import com.jluzh10.learning.web.converter.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author yzg
 * @create 2019/5/20
 * 用户行为相关控制器
 */
@Controller
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService usersService) {
        this.userService = usersService;
    }

    /**
     * 查询用户学习过的课程
     * @return
     */
    @RequestMapping(value = "study")
    @ResponseBody
    public ResponseData findStudy(@LoginUser User user,String orderBy){
        if (user!=null){
            List<Course> byStudy = userService.findByStudy(user.getId(), orderBy);
            return new ResponseData().success().data(byStudy);
        }
        return new ResponseData().fail();
    }


    /**
     * 访问自己的个人中心或者查看他人信息
     *
     * @param userId
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/i/{userId}")
    public ModelAndView personal(@PathVariable(value = "userId") int userId,
                                 ModelAndView modelAndView, @LoginUser User user) {
        System.out.println("user = " + user);
       if (user.getId()==userId){//访问个人中心
           modelAndView.setViewName("personal");
           user.setPassword(null);
           modelAndView.addObject("users",user);
       }else {//访问他人主页
           modelAndView.setViewName("others");
           user.setPassword(null);
           modelAndView.addObject("users",user);
       }
        return modelAndView;
    }

    /**
     * 收藏获取消收藏课程
     *
     * @param courseId 课程id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "collect/{isCollect}/{courseId}", method = RequestMethod.POST)
    @ResponseBody

    public ResponseData collectCourse(@PathVariable(value = "courseId") Integer courseId,
                                      @LoginUser User user,
                                      @PathVariable(value = "isCollect") boolean isCollect) throws Exception {
        if (user != null) {
            //收藏或取消收藏课程
            userService.collectCourse(user.getId(), courseId,isCollect);
            return new ResponseData().success();
        }
        return new ResponseData().fail("未登录");
    }


    /**
     * 注册用户
     *
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData register(User user) throws Exception {

        List<User> byUsername = userService.findByUsername(user.getUsername());
        if (byUsername.size() > 0) {//用户名已存在
            return new ResponseData().fail("用户名已存在");
        }
        List<User> byMobile = userService.findByMobile(user.getMobile());
        if (byMobile.size() > 0) {//手机号已注册
            return new ResponseData().fail("手机号已注册");
        }
        //保存用户
        userService.addUser(user);
        return new ResponseData().success("注册成功");
    }

    /**
     * 登陆请求
     * @param user
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData login(@RequestBody User user, HttpSession session) throws Exception {
        //查询用户名
        List<User> users = userService.findByUsername(user.getUsername());
        if (users.size() == 0) {
            return new ResponseData().fail("用户名不存在");
        }
        //校验密码
        if (!userService.checkPassword(user.getPassword(), users.get(0).getPassword())) {
            return new ResponseData().fail("密码错误");
        }
        //登陆成功
        session.setAttribute("user", users.get(0));
        //设置最后登录时间
        //更新用户信息
        userService.update(new User(users.get(0).getId(), new Date()));
        //存入session

        session.setAttribute("user", users.get(0));

        return new ResponseData().success("登陆成功");
    }

    /**
     * 访问登陆页面
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView toLogin(ModelAndView modelAndView) {
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * 访问注册页面
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.GET)
    public ModelAndView toRegister(ModelAndView modelAndView) {
        modelAndView.setViewName("register");
        return modelAndView;
    }
}
